package com.cqhfan.chatroom.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqhfan.chatroom.domain.dto.FriendAddDTO;
import com.cqhfan.chatroom.domain.po.Friend;
import com.cqhfan.chatroom.domain.po.NewFriend;
import com.cqhfan.chatroom.domain.po.User;
import com.cqhfan.chatroom.domain.vo.MyFriendVO;
import com.cqhfan.chatroom.domain.vo.NewFriendVO;
import com.cqhfan.chatroom.mapper.FriendMapper;
import com.cqhfan.chatroom.service.IFriendService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqhfan.chatroom.service.INewFriendService;
import com.cqhfan.chatroom.service.IUserService;
import com.cqhfan.common.domain.dto.PageDTO;
import com.cqhfan.common.domain.query.PageQuery;
import com.cqhfan.common.exceptions.BizException;
import com.cqhfan.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 好友 服务实现类
 * </p>
 *
 * @author 眭传洪
 * @since 2024-11-18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FriendServiceImpl extends ServiceImpl<FriendMapper, Friend> implements IFriendService {

    private final INewFriendService newFriendService;

    private final IUserService userService;

    @Override
    public PageDTO<NewFriendVO> listNewFriend(PageQuery query) {
        // 查询新朋友信息
        Long userId = UserContext.getUser();
        Page<NewFriend> page = newFriendService.lambdaQuery()
                .eq(NewFriend::getReceiverId, userId)
                .page(query.toMpPageByCreateTime());
        List<NewFriend> records = page.getRecords();
        if (CollUtil.isEmpty(records)) {
            return PageDTO.empty();
        }

        // 查询发送者信息
        List<Long> senderIds = records.stream().map(NewFriend::getSendId).toList();
        List<User> users = userService.lambdaQuery()
                .in(User::getId, senderIds)
                .list();
        if (CollUtil.isEmpty(users)) {
            throw new BizException("用户信息为空");
        }
        Map<Long, User> senderUserMap = users.stream().collect(Collectors.toMap(User::getId, u -> u));

        // 组装VO
        List<NewFriendVO> result = new ArrayList<>(records.size());
        for (NewFriend record : records) {
            Long friendId = record.getSendId();
            User user = senderUserMap.get(friendId);
            if (user == null) {
                continue;
            }
            NewFriendVO vo = new NewFriendVO();
            vo.setId(record.getId());
            vo.setFriendId(friendId);
            vo.setNickname(user.getNickname());
            vo.setValidInfo(record.getValidInfo());
            vo.setAvatar(user.getAvatar());
            vo.setApplyTime(record.getCreateTime());
            vo.setFinished(record.getFinished());
            result.add(vo);
        }

        return PageDTO.of(page.getPages(), page.getTotal(), result);
    }

    @Override
    public List<MyFriendVO> listMyFriends() {
        Long userId = UserContext.getUser();
        // 查询我的好友信息
        List<Friend> friends = lambdaQuery().eq(Friend::getMyId, userId).list();
        if (CollUtil.isEmpty(friends)) {
            return Collections.emptyList();
        }

        // 查询好友数据信息
        List<Long> friendIds = friends.stream().map(Friend::getFriendId).toList();
        List<User> users = userService.lambdaQuery().in(User::getId, friendIds).list();
        Map<Long, String> userAvatarMap = users.stream().collect(Collectors.toMap(User::getId, User::getAvatar));

        // 组装列表vo
        List<MyFriendVO> result = new ArrayList<>(friends.size());
        for (Friend friend : friends) {
            MyFriendVO vo = new MyFriendVO();
            Long friendId = friend.getFriendId();
            vo.setId(friendId);
            vo.setAvatar(userAvatarMap.get(friendId));
            vo.setRemark(friend.getRemark());
            result.add(vo);
        }

        return result;
    }

    @Override
    @Transactional
    public void addFriendInfo(FriendAddDTO body) {
        Long id = body.getId();
        Long friendId = body.getFriendId();
        String remark = body.getRemark();
        Long userId = UserContext.getUser();

        // 创建我是他的好友信息
        NewFriend newFriend = newFriendService.getById(id);
        if (newFriend == null) {
            throw new BizException("新朋友信息为空");
        }
        Friend friend = buildFriendInfo(friendId, userId, newFriend.getReceiverRemark());
        save(friend);

        // 创建他是我的好友信息
        friend = buildFriendInfo(userId, friendId, remark);
        save(friend);

        // 更新新朋友信息为完成
        newFriend.setUpdateTime(LocalDateTime.now());
        newFriend.setFinished(Boolean.TRUE);
        newFriendService.updateById(newFriend);
    }

    private Friend buildFriendInfo(Long myId, Long friendId, String remark) {
        Friend friend = new Friend();
        friend.setMyId(myId);
        friend.setFriendId(friendId);
        friend.setRemark(remark);
        friend.setIfBlack(Boolean.FALSE);
        friend.setCreateTime(LocalDateTime.now());
        return friend;
    }
}
